package cn.zhagzheguo.xk.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.zhagzheguo.xk.dao.CourseFileDao;
import cn.zhagzheguo.xk.model.CourseFile;
import cn.zhagzheguo.xk.status.CommonStatus;

@Repository
public class CourseFileDaoImpl implements CourseFileDao {

	@Autowired
	SqlSessionFactory sqlSessionFactory;

	@Override
	public int insert(CourseFile courseFile) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			session.insert("cn.zhagzheguo.xk.mapper.CourseFileMapper.insert", courseFile);
			session.commit();
			return CommonStatus.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			return CommonStatus.FAIL;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<CourseFile> getAllByCourseId(int course_id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			List<CourseFile> list = session.selectList("cn.zhagzheguo.xk.mapper.CourseFileMapper.selectList_course",
					course_id);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int delete(int courseFile_id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			session.delete("cn.zhagzheguo.xk.mapper.CourseFileMapper.delete", courseFile_id);
			session.commit();
			return CommonStatus.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			return CommonStatus.FAIL;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int addDownloadCount(String fileName) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			session.update("cn.zhagzheguo.xk.mapper.CourseFileMapper.addDownloadCount", fileName);
			session.commit();
			return CommonStatus.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			return CommonStatus.FAIL;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public static void main(String[] args) {
		CourseFileDao cf = new CourseFileDaoImpl();
		CourseFile c = new CourseFile();
		c.setCourse_id(2);
		c.setStu_id(1);
		c.setDate("2016-9-13 20:11");
		cf.insert(c);

		List<CourseFile> list = cf.getAllByCourseId(2);
		System.out.println(list.toString());
	}

}
